package com.qf.realm;

import com.qf.pojo.UserPojo;
import com.qf.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)  throws AuthenticationException {
        //真正的执行登录的位置；
        UsernamePasswordToken user = (UsernamePasswordToken)token;

        //怎么才能够够真正的完成这个认证的步骤呢？
        //必须去数据库查询这个用户
        //Userpojo userpojo : 从数据库查询过来的数据
        UserPojo userPojo = userService.selectUserByuname(user.getUsername());

        if(null == userPojo){ //用户为空
            throw new UnknownAccountException("用户为空");
        }

        //我们在这里不需要判断密码是否正确，因为整个认证过程需要交给shiro去完成；
        /**
         * principal
         * credentials
         * realmName
         */
        String principal = user.getUsername(); //帐号
        String credentials = userPojo.getUpass();  //从数据库获取的密码
        String realmName = super.getName(); //realm的名字

        //进行注册的时候加了 盐值； 登录的时候，对密码比对的时候，也必须加盐
        ByteSource bs = ByteSource.Util.bytes(principal); //使用用户名当作盐值


        AuthenticationInfo ai = new SimpleAuthenticationInfo(principal,credentials,bs,realmName);
        //AuthenticationInfo ai = new SimpleAuthenticationInfo();

        return ai;





    }
}
